package cn.iclass.modules.sys.service.impl;


import cn.iclass.common.constant.CommonConstant;
import cn.iclass.modules.sys.dao.SysMenuDao;
import cn.iclass.modules.sys.dao.SysRoleMenuDao;
import cn.iclass.modules.sys.dao.SysUserDao;
import cn.iclass.modules.sys.entity.SysMenuEntity;
import cn.iclass.modules.sys.entity.SysRoleMenuEntity;
import cn.iclass.modules.sys.service.SysMenuService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * @Description: 菜单管理
 * @Author: alan
 * @Date: 2019/6/10 5:25 PM
 */
@Service("sysMenuService")
public class SysMenuServiceImpl extends ServiceImpl<SysMenuDao, SysMenuEntity> implements SysMenuService {
	@Resource
	private SysUserDao sysUserDao;
	@Resource
	private SysRoleMenuDao sysRoleMenuDao;

	@Override
	public List<SysMenuEntity> queryListParentId(Long parentId, List<Long> menuIdList) {
		List<SysMenuEntity> menuList = queryListParentId(parentId);
		if (menuIdList == null) {
			return menuList;
		}

		List<SysMenuEntity> userMenuList = new ArrayList<>();
		for (SysMenuEntity menu : menuList) {
			if (menuIdList.contains(menu.getMenuId())) {
				userMenuList.add(menu);
			}
		}
		return userMenuList;
	}

	@Override
	public List<SysMenuEntity> queryListParentId(Long parentId) {
		return baseMapper.queryListParentId(parentId);
	}

	@Override
	public List<SysMenuEntity> queryNotButtonList() {
		return baseMapper.queryNotButtonList();
	}

	@Override
	public List<SysMenuEntity> getUserMenuList(Long userId) {
		//系统管理员，拥有最高权限
		if (userId == CommonConstant.SUPER_ADMIN) {
			return getAllMenuList(null);
		}
		//用户菜单列表
		List<Long> menuIdList = sysUserDao.queryAllMenuId(userId);
		return getAllMenuList(menuIdList);
	}

	@Override
	public void delete(Long menuId) {
		//删除菜单
		this.removeById(menuId);
		//删除菜单与角色关联
		sysRoleMenuDao.delete(new QueryWrapper<SysRoleMenuEntity>().lambda().eq(SysRoleMenuEntity::getMenuId, menuId));
	}

	/**
	 * 获取所有菜单列表
	 */
	private List<SysMenuEntity> getAllMenuList(List<Long> menuIdList) {
		//查询根菜单列表
		List<SysMenuEntity> menuList = queryListParentId(0L, menuIdList);
		//递归获取子菜单
		getMenuTreeList(menuList, menuIdList);

		return menuList;
	}

	/**
	 * 递归
	 */
	private List<SysMenuEntity> getMenuTreeList(List<SysMenuEntity> menuList, List<Long> menuIdList) {
		List<SysMenuEntity> subMenuList = new ArrayList<SysMenuEntity>();

		for (SysMenuEntity entity : menuList) {
			//目录
			if (entity.getType() == CommonConstant.MenuType.CATALOG.getValue()) {
				entity.setList(getMenuTreeList(queryListParentId(entity.getMenuId(), menuIdList), menuIdList));
			}
			subMenuList.add(entity);
		}

		return subMenuList;
	}
}
